#include <stdbool.h>
#include "problem.h"
#include "gaming.h"

extern int PLAYER_FINISHED;
GameState gamestate = PREPARE;

int isWinningMove(PointType board[9], int index, PointType type) 
{
    board[index] = type;

  
    int wins[8][3] = {
        {0,1,2},{3,4,5},{6,7,8}, 
        {0,3,6},{1,4,7},{2,5,8}, 
        {0,4,8},{2,4,6}          
    };

    for (int i = 0; i < 8; ++i) {
        int a = wins[i][0], b = wins[i][1], c = wins[i][2];
        if (board[a] == type && board[b] == type && board[c] == type) {
            board[index] = EMPTY;
            return 1;
        }
    }

    board[index] = EMPTY;
    return 0;
}


int GetNextAIMove(Point PieceBoard[9]) 
{
    PointType tempBoard[9];
    for (int i = 0; i < 9; ++i)
        tempBoard[i] = PieceBoard[i].type;

    
    for (int i = 0; i < 9; ++i) {
        if (tempBoard[i] == EMPTY && isWinningMove(tempBoard, i, BLACK))
            return i; 
    }
    for (int i = 0; i < 9; ++i) {
        if (tempBoard[i] == EMPTY && isWinningMove(tempBoard, i, WHITE))
            return i; 
    }

   
    if (tempBoard[4] == EMPTY)
        return 4;

    
    int corners[] = {0, 2, 6, 8};
    for (int i = 0; i < 4; ++i) {
        if (tempBoard[corners[i]] == EMPTY)
            return corners[i];
    }

 
    for (int i = 0; i < 9; ++i) {
        if (tempBoard[i] == EMPTY)
            return i;
    }

    return -1; 
}


void reboot(void)
{
	problem = STOP;
	gamestate = PREPARE;
	PLAYER_FINISHED = 0;
}

